package com.carleasoft.mps.adu.business.basicsInfo.excel;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Moko
 * @title: ConvertTemplatePath
 * @projectName mps
 * @description: 
 * @date 2022/4/1414:54
 */
public class ConvertTemplatePath {
    public static String convertTemplatePath(String path) {
         if (System.getProperties().getProperty("os.name").contains("Windows")) {
            return path;
         }

        Resource resource = new ClassPathResource(path);
        FileOutputStream fileOutputStream = null;
        String folder = System.getProperty("catalina.home");
        File tempFile = new File(folder + File.separator + path);
        if (tempFile.exists()) {
            return tempFile.getPath();
        }
        File parentFile = tempFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(resource.getInputStream());
            fileOutputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return tempFile.getPath();
    }
}
